package com.example.memory.servicde.impl;

import com.example.memory.entity.Content;
import com.example.memory.entity.File;
import com.example.memory.servicde.ContentService;
import com.example.memory.servicde.FileService;
import com.example.memory.servicde.UploadService;
import com.example.memory.util.FastImageInfo;
import com.example.memory.util.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class UploadServiceImpl implements UploadService {
    @Resource
    FileService fileService;
    @Resource
    ContentService contentService;

    @Override
    public void upload(MultipartFile[] files, String title, String content) {
        try {
            Content cont = Content.getInstance(title, content);
            contentService.insert(cont);

            List<File> fileList = new ArrayList<>(files.length);
            for (MultipartFile multipartFile : files) {
                File file = File.getInstance(multipartFile, cont.getId());

                FastImageInfo fastImageInfo = FastImageInfo.create(FileUtils.writeFile(multipartFile.getInputStream(), file.getPath(), file.getName()));
                file.setWidth(fastImageInfo.getWidth());
                file.setHeight(fastImageInfo.getHeight());
                fileList.add(file);
            }
            fileService.insertList(fileList);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
